<template>
  <!-- <el-pagination background layout="prev, pager, next" :total="1000" /> -->

  <el-button type="success" @click="addBtnFun">
    <el-icon><Plus /></el-icon>添加
    </el-button>

  <el-button @click="bigdel" type="danger">
    <el-icon><Delete /></el-icon>
    批量删除</el-button>
  <span v-show="multipleSelection.length > 0">已选择{{ multipleSelection.length }}</span>
  <el-table ref="multipleTableRef" :data="listone" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column label="图片">
      <template #default="scope">
        <!-- {{ scope.row }} -->
        <img class="scopeimg" :src="scope.row.carouselUrl" alt="">
      </template>
    </el-table-column>
    <el-table-column label="跳转链接">
      <template #default="scope">
        <!-- {{ scope.row.redirectUrl }} -->
        <el-text class="mx-1" type="primary">{{ scope.row.redirectUrl }}</el-text>
      </template>
    </el-table-column>

    <el-table-column prop="carouselRank" label="排序"></el-table-column>
    <el-table-column prop="createTime" label="添加时间"></el-table-column>



    <el-table-column label="操作">
      <template #default="scope">
        <!-- {{ scope.row.redirectUrl }} -->
        <el-button size="small" type="primary" @click="handlePut(scope.$index, scope.row)">
          修改
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>



  <!-- 弹框 -->
  <el-dialog v-model="dialogFormVisible" :title=title width="500" @closed="closed">
    <!-- 文件 -->

    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" status-icon>
      <el-form-item label="图片" prop="imageUrl">
        <el-upload class="avatar-uploader" action="http://backend-api-02.newbee.ltd/manage-api/v1/upload/file"
          :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
          :headers="{ Token }">
          <img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="Activity name" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>

      <el-form-item label="Activity name" prop="rank">
        <el-input v-model="ruleForm.rank" />
      </el-form-item>




      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
        <el-button @click="dialogFormVisible = false; carouselId = ''">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">
          取消
        </el-button>
      </div>
    </template> -->
  </el-dialog>

  <!-- 分页 -->

  <el-pagination background @current-change="currentChange" layout="prev, pager, next" :total="total" />


</template>





<script setup>
let carouselId = "";//id
let title = ref('添加')
import { onMounted, ref, reactive } from 'vue'
import { ElTable, ElMessage } from 'element-plus'
import { Plus,Delete} from '@element-plus/icons-vue'
let Token = localStorage.getItem("token");
import axios from '../../ajax';
let dialogFormVisible = ref(false)


const multipleTableRef = ref()
const multipleSelection = ref([])

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}



onMounted(() => {
  getdata(1)

})
let listone = ref([])
let total = ref(0)
let getdata = async (pageNumber) => {
  let { list, totalCount } = await axios.get('/carousels', {
    params: {
      pageNumber,
      pageSize: 10
    }
  })
  // console.log(res);
  // console.log(list);

  listone.value = list
  total.value = totalCount

}
let currentChange = (page) => {
  console.log(page);
  getdata(page)
}
let handleDelete = (i, row) => {
  console.log(row.carouselId);
  listone.value.splice(i, 1)
  getid([row.carouselId])
}
let getid = async (ids) => {//删除
  let res = await axios.delete('/carousels', {
    data: {
      ids
    }

  })
}





let bigdel = () => {//删除

  if (multipleSelection.value.length == 0) {
    // alert("未选择")
    ElMessage.error('未选择!')
  }

  let arry = []
  multipleSelection.value.map(item => arry.push(item.carouselId))

  multipleSelection.value.map(item => {
    listone.value.map((items, index) => {
      if (item.carouselId == items.carouselId) {
        console.log(index);
        listone.value.splice(index, 1)
      }
    })
  })


  getid(arry)
}




let addBtnFun = () => {//添加
  title.value = "添加"
  dialogFormVisible.value = true
  carouselId = '';
  ruleForm.imageUrl = ""
  ruleForm.name = ''
  ruleForm.rank = ""
};

//弹框
const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  console.log(response);
  ruleForm.imageUrl = response.data
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}


const ruleFormRef = ref()
const ruleForm = reactive({
  imageUrl: "",
  name: '',
  rank: ""
})


const rules = reactive({  // 表单验证
  name: [
    { required: true, message: '名字', trigger: 'blur' },
  ],
  rank: [
    { required: true, message: '排序不能', trigger: 'blur' },
  ],
  imageUrl: [
    { required: true, message: '图片不能为空', trigger: 'blur' },
  ],

})

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {//验证通过----ajax
      console.log('submit!')
      if (title.value == '添加') {
        submitfun()
      } else {
        submitfunput()
      }


    } else { // 验证失败
      console.log('error submit!', fields)
    }
  })
}

let submitfun = async () => {
  let res = await axios.post('/carousels', {
    carouselRank: ruleForm.rank,
    carouselUrl: ruleForm.imageUrl,
    redirectUrl: ruleForm.name
  })
  dialogFormVisible.value = false
  getdata(1);
}
let submitfunput = async () => {
  let res = await axios.put('/carousels', {
    carouselRank: ruleForm.rank,
    carouselUrl: ruleForm.imageUrl,
    redirectUrl: ruleForm.name,
    carouselId
  })
  dialogFormVisible.value = false
  getdata(1);
}
const closed = () => {
  resetForm(ruleFormRef.value)
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}


//修改
let handlePut = (index, row) => {
  title.value = '修改'
  console.log(row);
  dialogFormVisible.value = true
  carouselId = row.carouselId
  ruleForm.rank = row.carouselRank
  ruleForm.imageUrl = row.carouselUrl
  ruleForm.name = row.redirectUrl
}


</script>
<style lang="scss" scoped>
.scopeimg {
  width: 30px;
  height: 30px;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #999;
  line-height: 100px;
  text-align: center;
  font-size: 50px;
  color: #999;

  img {
    width: 100px;
    height: 100px;
  }
}

.el-form-item__label-wrap {
  margin-left: 0 !important;
}
</style>